package top.saplf.sileny.base.comm

import android.content.Context
import android.support.design.widget.CoordinatorLayout
import android.support.design.widget.CoordinatorLayout.Behavior
import android.support.v4.view.ViewCompat
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import top.saplf.library.ui.FloatingActionMenu


/**
 * @author Saplf
 */
class ScrollAwareFabBehavior : Behavior<FloatingActionMenu> {
    @Suppress("unused")
    constructor() : super()

    @Suppress("unused")
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)

    override fun onStartNestedScroll(
            coordinatorLayout: CoordinatorLayout,
            child: FloatingActionMenu,
            directTargetChild: View,
            target: View,
            nestedScrollAxes: Int
    ): Boolean = (nestedScrollAxes and ViewCompat.SCROLL_AXIS_VERTICAL) != 0

    override fun onNestedScroll(
            coordinatorLayout: CoordinatorLayout,
            child: FloatingActionMenu,
            target: View,
            dxConsumed: Int, dyConsumed: Int,
            dxUnconsumed: Int, dyUnconsumed: Int
    ) {
        if (dyConsumed > 0) {
            child.hide()
        } else {
            child.show()
        }
    }

    override fun onNestedFling(
            coordinatorLayout: CoordinatorLayout,
            child: FloatingActionMenu,
            target: View,
            velocityX: Float, velocityY: Float,
            consumed: Boolean): Boolean {
        if (!consumed) {
            if (velocityY > 0) {
                child.hide()
            } else {
                child.show()
            }
        }
        return false
    }

    override fun onAttachedToLayoutParams(lp: CoordinatorLayout.LayoutParams) {
        if (lp.dodgeInsetEdges == Gravity.NO_GRAVITY) {
            // If the developer hasn't set dodgeInsetEdges, lets set it to BOTTOM so that
            // we dodge any Snackbars
            lp.dodgeInsetEdges = Gravity.BOTTOM
        }
    }
}